<template>
  <el-drawer
    v-model="drawerVisible"
    title="班级群聊"
    direction="rtl"
    :before-close="handleClose"
    :size="drawerWidth"
    class="resizable-drawer"
  >
    <div class="resize-handle" @mousedown="startResize"></div>
    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" class="message-item">
          <div class="message-content" :class="{ 
            'message-self': message.isSelf || message.senderId === 0,
            'message-pending': message.pending 
          }">
            <div class="message-header">
              <span v-if="!(message.isSelf || message.senderId === 0)" class="username">
                {{ message.senderName || message.nickname || message.username || '未知用户' }}
              </span>
              <span class="time">{{ formatTime(message.time || message.createTime) }}</span>
            </div>
            <div class="message-text">{{ message.content }}</div>
            <div v-if="message.pending" class="message-status">发送中...</div>
            <div v-if="message.error" class="message-error">
              发送失败 <el-button type="text" @click="retryMessage(index)">重试</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="chat-input">
        <el-input
          v-model="newMessage"
          type="textarea"
          :rows="3"
          placeholder="输入消息..."
          @keyup.enter.ctrl="sendMessage"
          :maxlength="1000"
          show-word-limit
        />
        <el-button type="primary" @click="sendMessage" :loading="sending">{{ sending ? '发送中...' : '发送' }}</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import { sendChatMessage, getGroupMessages } from '@/apis/chat'
import { ElMessage, ElMessageBox } from 'element-plus'
import websocketService from '@/utils/websocket'

const props = defineProps({
  classroomId: {
    type: String,
    required: true
  }
})

const drawerVisible = ref(false)
const messages = ref([])
const newMessage = ref('')
const messagesContainer = ref(null)
const drawerWidth = ref('400px')
const isResizing = ref(false)
const startX = ref(0)
const startWidth = ref(0)
let chatSubscription = null
let wsConnected = ref(false)

// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

// 增加发送状态标记
const sending = ref(false);


// 格式化时间显示
const formatTime = (date) => {
  const now = new Date()
  
  // 处理无效日期的情况
  if (!date) {
    return '未知时间';
  }
  
  // 尝试转换日期
  let messageDate;
  try {
    // 如果是字符串日期，尝试解析
    if (typeof date === 'string') {
      // 检查是否是ISO格式的日期字符串
      if (date.includes('T') || date.includes('-')) {
        messageDate = new Date(date);
      } else {
        // 尝试将时间戳字符串转为数字
        messageDate = new Date(parseInt(date));
      }
    } else if (date instanceof Date) {
      // 如果已经是Date对象
      messageDate = date;
    } else if (typeof date === 'number') {
      // 如果是时间戳数字
      messageDate = new Date(date);
    } else {
      return '未知时间';
    }
    
    // 检查日期是否有效
    if (isNaN(messageDate.getTime())) {
      return '无效日期';
    }
  } catch (e) {
    console.error('日期解析错误:', e, date);
    return '无效日期';
  }
  
  // 获取今天的开始时间（0点0分0秒）
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  // 获取昨天的开始时间
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  
  // 格式化时分秒
  const timeStr = messageDate.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
  
  // 判断消息时间
  if (messageDate >= today) {
    // 今天的消息，只显示时分秒
    return timeStr
  } else if (messageDate >= yesterday) {
    // 昨天的消息
    return `昨天 ${timeStr}`
  } else if (messageDate.getFullYear() === now.getFullYear()) {
    // 今年但更早的消息
    return `${messageDate.getMonth() + 1}月${messageDate.getDate()}日 ${timeStr}`
  } else {
    // 去年的消息
    return `${messageDate.getFullYear()}年${messageDate.getMonth() + 1}月${messageDate.getDate()}日 ${timeStr}`
  }
}

// 处理新消息
const handleNewMessage = (message) => {

  // 判断是否是当前班级的消息
  const targetId = message.data?.groupId;
  if (targetId === props.classroomId) {
    // 转换消息格式为前端展示所需格式
    const processedMessage = {
      id: message.data?.messageId,
      groupId: message.data?.groupId,
      content: message.data?.content,
      senderId: message.data?.fromUserId === message.data?.toUserId ? 0 : 1,
      senderName: message.data?.fromUserName,
      createTime: message.data?.createTime,
      isSelf: message.data?.fromUserId === message.data?.toUserId
    };
    
    // 添加新消息到列表
    messages.value.push(processedMessage);
    
    // 滚动到底部
    nextTick(() => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
      }
    });
  }
}

// 注册 WebSocket 以接收实时消息
const setupChatConnection = () => {
  if (!props.classroomId) return;
  
  // 只注册消息接收处理函数，不处理发送
  websocketService.onMessageType('chat_message', handleNewMessage);
  
  // 设置连接状态变更回调
  websocketService.onConnectionStatusChange = (status) => {
    wsConnected.value = status;
    
    // 如果重新连接，可能需要刷新消息列表以获取离线期间的消息
    if (status && drawerVisible.value) {
      refreshMessages();
    }
  };
  
  // 返回清理函数
  chatSubscription = {
    unsubscribe: () => {
      // 清理消息处理和状态回调
      websocketService.messageCallbacks.delete('chat_message');
      websocketService.onConnectionStatusChange = null;
    }
  };
}

// 获取群组消息历史
const getChatList = async () => {
  try {
    const messagesData = await getGroupMessages(props.classroomId);
    
    // 正确处理空数组情况
    if (Array.isArray(messagesData)) {
      // 处理每条消息的时间格式
      messages.value = messagesData.map(processMessageTime);
      pagination.value.total = messagesData.length;
    } else if (messagesData && messagesData.rows) {
      // 兼容不同格式的返回数据
      messages.value = messagesData.rows.map(processMessageTime);
      pagination.value.total = messagesData.total || messagesData.rows.length;
    } else {
      // 如果没有任何数据，初始化为空数组（这不是错误情况）
      messages.value = [];
      pagination.value.total = 0;
      console.info('群组中没有聊天消息');
    }
    
    // 滚动到底部
    nextTick(() => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
      }
    })
  } catch (error) {
    // 只有在实际错误（如网络问题）时才显示错误提示
    console.error('获取群组消息失败:', error)
    ElMessage.error('获取聊天记录失败: ' + (error.message || '未知错误'));
    
    // 失败时初始化空消息列表
    messages.value = []
    pagination.value.total = 0;
  }
}

// 处理消息时间字段和其他必要字段
const processMessageTime = (message) => {
  if (!message) return message;
  
  // 创建消息的副本，避免修改原始对象
  const processedMessage = { ...message };
  
  // 确保 senderId 字段存在，默认为非自己发送的消息
  if (processedMessage.senderId === undefined || processedMessage.senderId === null) {
    processedMessage.senderId = 1; // 默认为他人消息
  }
  
  // 确保 isSelf 与 senderId 状态一致
  processedMessage.isSelf = processedMessage.senderId === 0;
  
  // 处理时间字段
  if (processedMessage.createTime) {
    try {
      // 尝试解析时间字符串
      const timestamp = new Date(processedMessage.createTime).getTime();
      if (!isNaN(timestamp)) {
        processedMessage.createTime = new Date(timestamp).toISOString();
      }
    } catch (e) {
      console.warn('无法解析消息时间:', processedMessage.createTime);
    }
  } else {
    // 如果没有时间字段，使用当前时间
    processedMessage.createTime = new Date().toISOString();
  }
  
  return processedMessage;
};

// 刷新消息列表
const refreshMessages = async () => {
  await getChatList();
}

// 修改发送消息函数
const sendMessage = async () => {
  // 验证消息内容
  const content = newMessage.value.trim();
  if (!content) return;
  
  // 消息长度检查
  if (content.length > 1000) {
    ElMessage.warning('消息长度不能超过1000字符');
    return;
  }
  
  // 设置发送状态
  sending.value = true;
  
  // 清空输入框
  const messageSent = newMessage.value;
  newMessage.value = '';
  
  try {
    // 发送消息
    const result = await sendChatMessage({
      classroomId: props.classroomId,
      content: messageSent
    });
    
    if (result) {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
        }
      });
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败: ' + (error.message || '未知错误'));
  } finally {
    // 无论成功失败，重置发送状态
    sending.value = false;
  }
};

// 重试发送失败的消息
const retryMessage = async (index) => {
  const message = messages.value[index];
  
  // 重置消息状态
  message.pending = true;
  message.error = false;
  
  // 设置发送状态
  sending.value = true;
  
  try {
    // 重新发送消息
    const result = await sendChatMessage({
      classroomId: props.classroomId,
      content: message.content
    });
    
    // 如果服务器返回了消息对象，使用它替换当前消息
    if (result) {
      // 设置消息为自己发送的
      result.isSelf = true;
      result.senderId = 0; // 确保标记为自己的消息
      
      messages.value[index] = result;
    } else {
      // 如果没有返回消息对象，只更新状态
      message.pending = false;
    }
  } catch (error) {
    console.error('重新发送消息失败:', error);
    
    // 失败，标记错误
    message.pending = false;
    message.error = true;
    
    ElMessage.error('重新发送消息失败: ' + (error.message || '未知错误'));
  } finally {
    sending.value = false;
  }
};



// 打开抽屉时加载消息
const open = async () => {
  drawerVisible.value = true;
  
  // 设置WebSocket连接
  setupChatConnection();
  
  // 获取历史消息
  await getChatList();
}

// 关闭抽屉
const close = () => {
  drawerVisible.value = false
  
  // 清理聊天订阅
  if (chatSubscription) {
    chatSubscription.unsubscribe()
    chatSubscription = null
  }
}

// 处理关闭
const handleClose = (done) => {
  close()
  done()
}

// 调整宽度相关方法
const startResize = (e) => {
  isResizing.value = true
  startX.value = e.clientX
  startWidth.value = parseInt(drawerWidth.value)
}

const handleMouseMove = (e) => {
  if (!isResizing.value) return
  
  const deltaX = e.clientX - startX.value
  const newWidth = startWidth.value - deltaX // 因为是右侧抽屉，所以用减法
  
  // 限制最小和最大宽度
  if (newWidth >= 300 && newWidth <= 800) {
    drawerWidth.value = `${newWidth}px`
  }
}

const stopResize = () => {
  isResizing.value = false
}

// 添加鼠标事件监听
onMounted(() => {
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', stopResize)
})

// 移除事件监听和订阅
onUnmounted(() => {
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', stopResize)
  
  // 取消消息订阅
  if (chatSubscription) {
    chatSubscription.unsubscribe()
    chatSubscription = null
  }
})

// 暴露方法给父组件
defineExpose({
  open,
  close,
  refreshMessages
})
</script>

<style scoped>
.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f7fa;
}

.message-item {
  margin-bottom: 15px;
}

.message-content {
  max-width: 80%;
  padding: 10px;
  border-radius: 8px;
  background-color: #fff;
}

.message-self {
  margin-left: auto;
  background-color: #e6f7ff;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 12px;
}

/* 自己发送的消息，时间戳靠右显示 */
.message-self .message-header {
  justify-content: flex-end;
}

.username {
  font-weight: bold;
  color: #333;
}

.time {
  color: #999;
}

.message-text {
  word-break: break-word;
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  background-color: #fff;
}

.chat-input .el-button {
  margin-top: 10px;
  width: 100%;
}

.resize-handle {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  cursor: ew-resize;
  background-color: transparent;
  z-index: 1000;
}

.resize-handle:hover {
  background-color: rgba(0, 0, 0, 0.1);
}

:deep(.el-drawer) {
  transition: width 0.3s ease;
}

.message-pending {
  opacity: 0.7;
}

.message-status {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.message-error {
  font-size: 12px;
  color: #ff4949;
  margin-top: 4px;
  text-align: right;
}
</style> 